package com.xdja.study;

import com.alibaba.fastjson.JSON;
import com.xdja.study.mysql.UserHandler;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.eventbus.DeliveryOptions;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class HttpRouteVerticle extends AbstractVerticle {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    AppConfiguration configuration;
    @Autowired
    private UserHandler userHandler;

    @Override
    public void start() {
        //1.获取router
        Router router = Router.router(vertx);
        //2.静态页面处理
//        router.route().handler(StaticHandler.create());
        //3.各api接口处理
        router.route().handler(BodyHandler.create());
        router.get().handler(BodyHandler.create());
//        router.get("/user/:userId").handler(userHandler::getUser);
        router.get("/mysql/user/:userId").handler(this::getMysqlUser);
        router.get("/redis/user/:userId").handler(this::getRedisUser);
        router.get("/http/client").handler(this::httpClient);
        router.get("/file/download").handler(this::downloadFile);
        //4.启动http服务
        vertx.createHttpServer().requestHandler(router).listen(configuration.httpPort());
    }

    /**
     * 通过mysql获取用户信息
     * @param context
     */
    private void getMysqlUser(RoutingContext context) {
        //1.获取请求参数
        String userId = context.request().getParam("userId");
        DeliveryOptions options = new DeliveryOptions();
        options.addHeader("userId", userId);
        JsonObject request = new JsonObject();
        vertx.eventBus().send("user.dao", request, options, reply -> {
            if (reply.succeeded()) {
                JsonObject body = (JsonObject) reply.result().body();
                this.returnResponse(context, body);
            } else {
                logger.error("失败");
                context.fail(reply.cause());
            }
        });
    }

    /**
     * 从redis中获取用户信息
     * @param context
     */
    private void getRedisUser(RoutingContext context) {
        //1.获取请求参数
        String userId = context.request().getParam("userId");
        DeliveryOptions options = new DeliveryOptions();
        options.addHeader("userId", userId);
        JsonObject request = new JsonObject();
        vertx.eventBus().send("user.redis", request, options, reply -> {
            if (reply.succeeded()) {
                JsonObject body = (JsonObject) reply.result().body();
                this.returnResponse(context, body);
            } else {
                logger.error("失败");
                context.fail(reply.cause());
            }
        });
    }

    /**
     * http调用
     * @param context
     */
    private void httpClient(RoutingContext context) {
        DeliveryOptions options = new DeliveryOptions();
        JsonObject request = new JsonObject();
        vertx.eventBus().send("http.client", request, options, reply -> {
            if (reply.succeeded()) {
                JsonObject body = (JsonObject) reply.result().body();
                this.returnResponse(context, body);
            } else {
                logger.error("失败");
                context.fail(reply.cause());
            }
        });
    }

    /**
     * 文件下载
     * @param context
     */
    private void downloadFile(RoutingContext context) {
        HttpServerResponse response = context.response();
        response.putHeader("contentType", "application/force-download");
        response.putHeader("Content-Disposition", "attachment;fileName=111.txt");
        response.sendFile(configuration.fileUrl());
    }

    /**
     * 返回结果内容
     * @param context
     * @param body
     */
    private void returnResponse(RoutingContext context, JsonObject body) {
        HttpServerResponse response = context.response();
        response.putHeader("content-type", "application/json;charset=UTF-8").end(JSON.toJSONString(body));
    }
}
